import { DownOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Dropdown, Menu, message, Switch, Divider, Icon, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import ConfigForm, { FormValueType } from './components/ConfigForm';
import { ListItem } from './data';
import { queryRule, addItemRule, updateRule, addRule, removeRule, removeItemRule, queryItemRule, updateItemRule } from './service';
import moment from 'moment';
import { Dispatch } from 'redux';
import { bdExec } from '@/helpers/RequestHelper';
import styles from './styles.less';
import ConfigItemForm from './components/ConfigItemForm';
import * as tsxHelper from '@/helpers/TsxHelper';

interface RoleListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
}

/**
 * 添加节点
 */
const handleAdd = async (fields: FormValueType) => {
  return bdExec({fn: addRule, args: fields, successMsg: '添加成功',failMsg: '添加失败请重试！'});
};

const handleAddItem = async (fields: FormValueType) => {
  return bdExec({fn: addItemRule, args: fields, successMsg: '添加成功',failMsg: '添加失败请重试！'});
};

/**
 * 更新节点
 */
const handleUpdate = async (fields: FormValueType) => {
  return bdExec({fn: updateRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};

const handleUpdateItem = async (fields: FormValueType) => {
  return bdExec({fn: updateItemRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};

/**
 *  删除节点
 */
const handleRemove = async (selectedRows: any[]) => {
  if (!selectedRows) return true;
  const ids:any = selectedRows.toString();
  return bdExec({fn: removeRule, args: {ids}, successMsg: '删除成功，即将刷新',failMsg: '删除失败，请重试！', hasLoading: false});
};

const handleRemoveSingle = async (ids: string) => {
  return bdExec({fn: removeRule, args: {ids}, successMsg: '删除成功，即将刷新',failMsg: '删除失败，请重试！'});
};

const handleRemoveItemSingle = async (ids: string) => {
  return bdExec({fn: removeItemRule, args: {ids}, successMsg: '删除成功，即将刷新',failMsg: '删除失败，请重试！', hasLoading: false});
};

const RoleList: React.FC<RoleListProps> = (props) => {

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [itemModalVisible, setItemModalVisible] = useState<boolean>(false);
  const [isExpand, setIsExpand] = useState<boolean>(false);
  const [oneLevelIds, setOneLevelIds] = useState<any[]>([]);
  const [expandedRowKeys, setExpandedRowKeys] = useState<any[]>([]);
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [isUpdate, setIsUpdate] = useState<boolean>(false);
  const [radioType, setRadioType] = useState<string | 'layout'| 'component' | 'redirect'>('component');
  const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);
  const [parentId, setParentId] = useState<number>(0);
  const [parentName,setParentName] = useState<String>('');
  const [stateData, setStateData] = useState<any>({data: {}});
  const [treeData,setTreeData] = useState<any>()
  const actionRef = useRef<ActionType>();
  const itemActionRef = useRef<ActionType>();


  const itemColumns: ProColumns<ListItem>[] = [
    {
      title: '权限名称',
      dataIndex: 'name',
    },
    {
      title: '权限标识',
      dataIndex: 'nickname',
    },
    {
      title: '描述',
      dataIndex: 'remark',
    },
    {
      title: '类型',
      dataIndex: 'type',
    },
    {
      title: '是否启用',
      dataIndex: '',
      render: (_, record) => (
        <Switch checked={record.is_enable} onChange={async () => {
          let s = await handleUpdateItem({id: record.id, is_enable: (!record.is_enable).toString()});
          s && itemActionRef.current?.reload();
        }} />
      )
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'right',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setItemModalVisible(true);
              setIsUpdate(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              tsxHelper.showDeleteConfirm(
                'danger',
                handleRemoveItemSingle,
                record.id.toString(),
                () => {
                  setRowKeys([]);
                  itemActionRef.current?.reload()
                }
              )  
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];
  
  const columns:ProColumns<ListItem>[] = [
    {
      title: '描述',
      dataIndex: 'remark',
    },
    {
      title: '类型',
      dataIndex: 'type',
      hideInSearch: true,
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
    },
    // {
    //   title: '标识',
    //   dataIndex: 'nickname',
    //   hideInSearch: true,
    // },
    {
      title: 'path',
      dataIndex: 'menu_path',
      hideInSearch: true,
    },
    {
      title: '隐式菜单',
      dataIndex: 'is_show',
      hideInSearch: true,
      renderText: (val:any) => {
        return val === 1 ? '否':'是';
      }
    },
    {
      title: '是否启用',
      dataIndex: '',
      render: (_, record) => (
        <Switch checked={record.is_enable} onChange={async () => {
          let s = await handleUpdate({id: record.id, is_enable: (!record.is_enable).toString()});
          console.log('actionRef.current->',actionRef.current)
          s && actionRef.current?.reload();
        }} />
      )
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      sorter: true,
      hideInSearch: true,
      render: (val:any) => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_:any, record:ListItem) => (
        <>
          <a
            onClick={() => {
              initValuesData(record);
            }}
          >
            编辑
          </a>
          { record.type === 'component' &&
           <>
            <Divider type="vertical" />
            <a onClick={() => {
              setDrawerVisible(true);
              setParentId(record.id);
              setParentName(record.remark || '');
            }}>
              <Icon type='setting'style={{marginRight: 6}}/>菜单权限
            </a>
           </>
          }
        </>
      ),
    },
  ];

  const initValuesData = (record:any) => {
    handleModalVisible(true);
    setIsUpdate(true);
    setStepFormValues(record);
    setRadioType(record.type);
  }

  const getListData = (params:any) => {
    if(params&&(params.name || params.remark)){
      if(params.remark){
        return tsxHelper.handleSearchTreeData(treeData,params.remark)
      }else if(params.name){
        return tsxHelper.handleSearchTreeData(treeData,params.name)
      }    
    }else {
      return queryRule(params).then((res:any) => {
        if(res.code === 0){
          setStateData(res.data)
          // 获取所有一级分类的id
          let ids:any = [];
          res.data.listData.data.forEach((v:any) => {
            ids.push(v.id);
          })
          setOneLevelIds(ids);
          setTreeData(res.data.listData.data);
          return res.data.listData;
        }else{
          message.error(res.msg);
        }
      })
    }
  }

  const fetchItemListById = (params:any) => {
    return queryItemRule(params).then((res:any) => {
      if(res.code === 0){
        return res.data.listData;
      }else{
        message.error(res.msg);
      }
    })
  }


  const handleExpandAll = (isExpand:boolean) => {
    if(!isExpand){
      let allIds:any[] = [];
      stateData.listData.data.forEach((item:any) => {
        if(item.childrenIds && item.childrenIds.length > 0){
          allIds = [item.id, ...allIds, ...item.childrenIds];
        }
      })
      setExpandedRowKeys(allIds);
      setIsExpand(true);
    }else{
      setExpandedRowKeys([]);
      setIsExpand(false);
    }
  }

  const handleExpandedRowsChange = (expandedRows:string[]|number[]) => {
    setExpandedRowKeys(expandedRows);
    let expandedStatus = false;
    oneLevelIds.forEach((id:number) => {
      // 如果有一个一级id存在于expandedRows中，就说明是展开的状态，isExpand该为true;
      if(expandedRows.toString().indexOf(id.toString()) > -1){
        expandedStatus = true;
      }
    })
    // 设置当前分类是否为展开状态： true为展开
    setIsExpand(expandedStatus);

  }

  const handleChangeType = (value:any) => {
    setRadioType(value)
  }

  const handleOnSubmit = (value:FormValueType) => {
    return new Promise((resolve, reject) => {
      let s = isUpdate ? handleUpdate(value) : handleAdd(value);
      resolve(s);
    }).then( status => {
      if(status){
        handleModalVisible(false);
        setRadioType('component');
        
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
      return status; // 返回执行结果:boolean, 子组件接收此值来重置数据
    })
  }

  const handleOnSubmitItem = (value:FormValueType) => {
    return new Promise((resolve, reject) => {
      let s = isUpdate ? handleUpdateItem(value) : handleAddItem(value);
      resolve(s);
    }).then( status => {
      if(status){
        setItemModalVisible(false);
        if (itemActionRef.current) {
          itemActionRef.current.reload();
        }
      }
      return status;
    })
  }


  return (
    <PageHeaderWrapper>
      
      <ProTable<any>
            headerTitle={''}
            actionRef={actionRef}
            rowKey="key"
            search={true}
            
            pagination={false}
            toolBarRender={(action, { selectedRowKeys, selectedRows }) => [
              <Button icon={isExpand ? 'minus':'plus'} 
                onClick={() => {
                  handleExpandAll(isExpand);
                }}
              >
                {isExpand ? '收起':'展开'}
              </Button>,
              <Button icon={'plus'} type="primary" 
                onClick={() => {
                  handleModalVisible(true)
                  setIsUpdate(false);
                }}
              >
                新建
              </Button>,
              selectedRowKeys && selectedRowKeys.length > 0 && (
                <Dropdown
                  overlay={
                    <Menu
                      onClick={async e => {
                        if (e.key === 'remove') {
                          tsxHelper.showDeleteConfirm(
                            'danger',
                            handleRemove,
                            selectedRowKeys,
                            () => {
                              setRowKeys([]);
                              action.reload();
                            }
                          )                       
                        }
                      }}
                      selectedKeys={[]}
                    >
                      <Menu.Item key="remove">批量删除</Menu.Item>
                    </Menu>
                  }
                >
                  <Button>
                    批量操作 <DownOutlined />
                  </Button>
                </Dropdown>
              ),
            ]}
            tableAlertRender={(selectedRowKeys, selectedRows) => (
              <div>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
              </div>
            )}
            request={(params) => getListData(params)}
            // 这个参数会自动注入到params中去，如果selectIndex修改， 还会触发reload()
            params={{}}
            columns={columns}
            rowSelection={{
              onChange: (selectedRowKeys, selectedRows) => {
                setRowKeys(selectedRowKeys);
              },
              selectedRowKeys: rowKeys,
            }}
            defaultExpandAllRows={true}
            expandRowByClick={false}
            expandedRowKeys={expandedRowKeys}
            onExpand={(expanded, record) => {
              console.log(expanded, record)
            }}
            onExpandedRowsChange={(expandedRows) => handleExpandedRowsChange(expandedRows)}
          />
          
      { createModalVisible && 
      <ConfigForm
        onSubmit={(value) => handleOnSubmit(value)}
        onCancel={() => {
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
        handleChangeType={handleChangeType}
        values={stepFormValues}
        otherValues={{
          common: stateData.common || {},
          isUpdate,
          radioType,
          parentId
        }}
      />
      }

      {drawerVisible &&
      <Drawer
        // title={`菜单: ${parentName}`}
        placement="right"
        width="39%"
        closable={false}
        onClose={() => setDrawerVisible(false)}
        visible={drawerVisible}
        className={styles.dbDrawer}
      >
        <ProTable<any>
          headerTitle={`菜单:${parentName}`}
          actionRef={itemActionRef}
          rowKey="key"
          search={false}
          pagination={false}
          toolBarRender={(action, { selectedRows }) => [
            <Button icon={'plus'} type="primary" 
              onClick={() => {
                setItemModalVisible(true);
                setIsUpdate(false);
              }}
            >
              新建
            </Button>
          ]}
          request={(params) => fetchItemListById(params)}
          params={{
            menu_id: parentId
          }}
          columns={itemColumns}
        />
      </Drawer>
      }
      {itemModalVisible && 
      <ConfigItemForm
        onSubmit={(value) => handleOnSubmitItem(value)}
        onCancel={() => {
          setItemModalVisible(false);
          handleModalVisible(false);
        }}
        itemModalVisible={itemModalVisible}
        values={stepFormValues}
        otherValues={{
          common: stateData.common || {},
          isUpdate,
          parentId
        }}
      />
      }
      
    </PageHeaderWrapper>
  );
};

export default Form.create<RoleListProps>()(RoleList);
